import 'package:flutter/material.dart';
import 'package:flutter_city_picker/city_picker.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import '../../application.dart';
import '../../models/member_address_model.dart';
import '../../utils/city_picker_driver.dart';
import '../../utils/tools.dart';
import '../../tbicons.dart';
import '../../utils/api.dart';

class MemberAddressDetailPage extends StatefulWidget {
  final int addressId;
  final bool onSuccessQuit;

  MemberAddressDetailPage({
    Key? key,
    Map<String, dynamic>? arguments,
    this.onSuccessQuit = true,
  })  : addressId = arguments?['id'] ?? 0,
        super(key: key);

  @override
  State<StatefulWidget> createState() => _MemberAddressDetailPageState();
}

class _MemberAddressDetailPageState extends State<MemberAddressDetailPage> {
  MemberAddressModel address = MemberAddressModel();
  final _cityPickerListener = CityPickerDriver();
  bool _isLoading = false;
  bool _isSubmitting = false;

  final TextEditingController _areaController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _cityPickerListener.on<CityPickerResult>().listen((event) {
      address.province = event.provinceName ?? '';
      address.city = event.cityName ?? '';
      address.area = event.districtName ?? '';
      setState(() {
        _areaController.value = TextEditingValue(text: address.areaView);
      });
    });
    if (widget.addressId > 0) {
      _isLoading = true;
      loadAddress();
    }
  }

  @override
  dispose() {
    _cityPickerListener.destroy();
    super.dispose();
  }

  showAreaPicker() {
    CityPicker.show(context: context, cityPickerListener: _cityPickerListener);
  }

  loadAddress() async {
    final result =
        await Api.get('member.address/view', {'id': widget.addressId});
    if (result.code == 1) {
      address = MemberAddressModel.fromJson(result.data);
      setState(() {
        _isLoading = false;
        _areaController.value = TextEditingValue(text: address.areaView);
      });
    } else {
      MyDialog.toast(result.message);
      if (result.needLogin) {
        app.route('/login');
      }
    }
  }

  saveAddress() async {
    if (address.receiveName.isEmpty) {
      MyDialog.toast('请填写收货人');
      return;
    }
    if (address.mobile.isEmpty) {
      MyDialog.toast('请填写联系电话');
      return;
    }
    if (address.area.isEmpty) {
      MyDialog.toast('请选择所在区域');
      return;
    }
    if (address.address.isEmpty) {
      MyDialog.toast('请填写详细地址');
      return;
    }
    if (_isSubmitting) return;
    _isSubmitting = true;
    final controller = MyDialog.loading('正在保存');
    final navigator = Navigator.of(context);
    final result = await Api.post(
      'member.address/save',
      {'address': address.toJson(), 'id': address.id},
    );
    _isSubmitting = false;
    controller.close();
    if (result.code == 1) {
      MyDialog.toast('保存成功');
      if (widget.onSuccessQuit) {
        navigator.pop();
      }
    } else {
      MyDialog.toast(result.message);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.addressId > 0 ? '编辑收货地址' : '添加收货地址'),
        actions: <Widget>[
          TextButton(
            onPressed: () {
              saveAddress();
            },
            child: const Text(
              '保存',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: _isLoading
            ? const Center(
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  color: Colors.black26,
                ),
              )
            : Container(
                padding: const EdgeInsets.all(8),
                child: Form(
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  child: ListView(
                    children: <Widget>[
                      TextFormField(
                        initialValue: address.receiveName,
                        onChanged: (newValue) {
                          address.receiveName = newValue;
                        },
                        decoration: const InputDecoration(
                          prefixIcon: Icon(Tbicons.my_light),
                          hintText: '收货人',
                        ),
                      ),
                      const SizedBox(height: 10),
                      TextFormField(
                        initialValue: address.mobile,
                        onChanged: (newValue) {
                          address.mobile = newValue;
                        },
                        validator: (value) {
                          return Tools.isMobile(value) ? null : '请填写手机号码';
                        },
                        decoration: const InputDecoration(
                          prefixIcon: Icon(Tbicons.phone_light),
                          hintText: '联系电话',
                        ),
                      ),
                      const SizedBox(height: 10),
                      TextFormField(
                        controller: _areaController,
                        readOnly: true,
                        onTap: showAreaPicker,
                        decoration: const InputDecoration(
                          prefixIcon: Icon(Tbicons.location_light),
                          hintText: '所在地区',
                        ),
                      ),
                      const SizedBox(height: 10),
                      TextFormField(
                        initialValue: address.address,
                        onChanged: (newValue) {
                          address.address = newValue;
                        },
                        decoration: const InputDecoration(
                          hintText: '详细地址',
                        ),
                      ),
                      const SizedBox(height: 10),
                      SwitchListTile(
                        value: address.isDefault,
                        title: const Text('是否设为默认地址'),
                        onChanged: (newVal) {
                          setState(() {
                            address.isDefault = newVal;
                          });
                        },
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }
}
